#!/usr/bin/env python

# Copyright 2012, Alexandros Tsourakis <alexandros.tsourakis@se.teleperformance.com>.
# All rights reserved.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/


"""
Check plugin for Nagios or any Nagios compatible system to check the time elapsed from the last
insert on a MySQL table.

This plugin depends on the existence of a TIMESTAMP type column on the table you want to check.
For more information check http://dev.mysql.com/doc/refman/5.0/en/timestamp-initialization.html

Example usage:

* Check in localhost without authentication.
  The database is 'statsdb', the table is 'realtimetb' and teh TIMESTAMP column is 'time':

    check_dbrecords.py statsdb realtimetb time

* Check in host db01.example.com with username 'admin' and password 'secure'.
  The database is 'statsdb', the table is 'realtimetb' and teh TIMESTAMP column is 'time':

    check_dbrecords.py -H db01.example.com -u admin -p secure statsdb realtimetb time

"""

__title__ = "check_dbrecords"
__version__ = "0.1.0"

import sys
try:
    import MySQLdb
except Exception, error:
    print "ERROR!", error
    sys.exit(1)

from time import time
import argparse


def get_table_rec():
    """Where we connect to the database and fetch the last record"""
    db = MySQLdb.connect(host = mysql_host,
                        user = mysql_user,
                        passwd = mysql_pass,
                        db = use_db)
    cursor = db.cursor()
    cursor.execute("SELECT id, UNIX_TIMESTAMP(%s) as created FROM %s.%s ORDER BY id DESC LIMIT 1"
               % time_column, use_db, db_table)
    result = cursor.fetchone()
    cursor.close()
    db.close()
    return result


def check_result():
    """Where we check to see if the last record is too old"""
    last_time = get_table_rec()[1]
    time_diff = abs(time() - last_time)
    output = "Last entry age is %s sec" % round(time_diff, 1)
    perfdata = "'Entry Age'=%ss" % round(time_diff, 1)
    if time_diff > critical_age:
        print "Critical - %s | %s" % output, perfdata
        return 2
    if time_diff > warning_age:
        print "Warning - %s | %s" % output, perfdata
        return 1
    elif time_diff < warning_age:
        print "OK - %s | %s" % output, perfdata
        return 0
    else:
        print "Unknown result"
        return 3



"""Defines the command line arguments and assigns the options."""
# Configure the command line arguments
parser = argparse.ArgumentParser()

parser.add_argument("-V", "--version", action = "version", version = __version__,
                    help = "Display the plugin version")

parser.add_argument("database",
                    help = "The name of the database to use.")

parser.add_argument("table",
                    help = "The table that we're going to check.")

parser.add_argument("column",
                    help = "The TIMESTAMP type column.")

parser.add_argument("-H", "--host", default = "localhost",
                    help = "The database server IP or hostname. If nothing is specified it will use localhost.")

parser.add_argument("-u", "--user",
                    help = "The username to connect with. If nothing is specified it will try without authentication.")

parser.add_argument("-p", "--password",
                    help = "The password to use.")

parser.add_argument("-w", "--warning", default = 30,
                    help = "The warning threshold in seconds. Default is 30.")

parser.add_argument("-c", "--critical", default = 60,
                    help = "The critical threshold in seconds, Default is 60.")
args = parser.parse_args()

# Assign the command line input
use_db = args.database
db_table = args.table
time_column = args.column
mysql_host = args.host
mysql_user = args.user
mysql_pass = args.password
critical_age = args.critical
warning_age = args.warning

# Do what we're supposed to do
check_result()
print use_db, db_table, time_column, mysql_host, mysql_user, mysql_pass, critical_age, warning_age


